<template>
    <div id="chartRef2" class="chart-container"></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import titleIcon from '@/assets/images/titleIcon.png';
defineOptions({ name: 'StackedAreaChart' })

const props = defineProps({
    data: {
        type: Array,
    },
})
const colorList = ref([
  '#55B68B',
  '#69D0FF',
  '#FA880E'
])
// 动态生成渐变色
function getGradientColor(index: number): echarts.graphic.LinearGradient {
  let startColor: string;
  let endColor: string;
  switch (index) {
    case 0:
      startColor = '#55B68B';
      endColor = '#4EA775';
      break;
    case 1:
      startColor = '#3560F6';
      endColor = '#69D0FF';
      break;
    case 2:
      startColor = '#FA880E';
      endColor = '#F4BA43';
      break;
  }
  return new echarts.graphic.LinearGradient(
    0, 0, 0, 1, // 渐变方向，从上到下
    [
      { offset: 0, color: startColor }, // 起始颜色
      { offset: 1, color: endColor },  // 结束颜色
    ]
  );
}
function getColor(index: number): echarts.graphic.LinearGradient {
  let startColor: string;
  let endColor: string;
  switch (index) {
    case 0:
      startColor = '#55B080';
      endColor = 'rgba(48, 201, 201, 0)';
      break;
    case 1:
      startColor = 'rgba(95,164,237, 0.5)';
      endColor = 'rgba(123,170,224, 1)';
      break;
    case 2:
      startColor = 'rgba(237, 168, 95, 0.5)';
      endColor = 'rgba(224, 187, 123, 0)';
      break;
  }
  let item = {
    type: 'linear',
    x: 0,
    y: 0,
    x2: 0,
    y2: 1,
    colorStops: [
      { offset: 0, color: startColor },
      { offset: 1, color: endColor },
    ],
    global: false
  }
  return item
}
const initChart = () => {
    let flag = props.data[0]?.month.length == 1;
    let myChart = echarts.init(document.getElementById("chartRef2"))
    let xlabel: any = []
    let series: any = []

    if (props.data.length > 0) {
        xlabel = props.data[0].month.map((item)=> item.month);
        props.data.forEach((dataset,index) => {
            series.push({
                name: dataset.magnitudeRange,
                type: 'line',
                smooth: true,
                showSymbol:flag, // 不显示数据点
                // emphasis: {
                //     focus: 'series',
                // },
                emphasis: {
                  itemStyle: {
                    color: getGradientColor(index)
                  }
                },
                lineStyle: {
                    color: getGradientColor(index)
                },
                areaStyle:{
                    color:getColor(index),
                    opacity: 1,
                },
                data: dataset.month.map(item=> item.count),
            })
        })
    } else {
        series = [
            {
                name: '',
                type: 'line',
                smooth: true,
                areaStyle: {
                    opacity: 0.5,
                },
                emphasis: {
                    focus: 'series',
                },
                data: [],
            },
            {
                name: '',
                type: 'line',
                smooth: true,
                areaStyle: {
                    opacity: 0.5,
                },
                emphasis: {
                    focus: 'series',
                },
                data: [],
            },
            {
                name: '',
                type: 'line',
                smooth: true,
                areaStyle: {
                    opacity: 0.5,
                },
                emphasis: {
                    focus: 'series',
                },
                data: [],
            },
        ]
    }

    const option = {
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        title: {
            text:  `{icon|}{text|地震统计}`,
            textStyle: {
                rich: {
                    icon: {
                        backgroundColor: {
                            image: titleIcon
                        },
                        width: 16,
                        height: 16,
                        align: 'center',
                        verticalAlign: 'middle',
                    },
                    text: {
                        color: '#333',
                        fontSize: 16,
                        align: 'left',
                        verticalAlign: 'middle',
                        padding:[4, 0, 0, 4]
                    }
                }
            },
            left: 'left',
            top: 'top'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                let tooltipHtml = '<div>';
                params.forEach(param => {
                  const color = colorList.value[param.componentIndex]; // 获取当前数据项的颜色
                  console.log(color,'color');
                  
                  const seriesName = param.seriesName;
                  const value = param.value;
                  tooltipHtml += `
                    <div>
                      <span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:${color};"></span>
                      ${seriesName}: ${value}
                    </div>
                  `;
                });
                tooltipHtml += '</div>';
                return tooltipHtml;
            }
        },
        legend: {
            data: props.data.map((dataset, index) => ({
              name: dataset.magnitudeRange,
              textStyle: {
                color: '#333333' // 默认黑色文字
              },
              itemStyle: {
                color: getGradientColor(index), // 图例颜色
              },
              icon: 'roundRect',
              symbolSize: 10,
            })),
            right: '2%',

        },
        xAxis: {
            boundaryGap: false,
            type: 'category',
            data: xlabel,
            axisTick:{
                show: false
            },
            axisLine: {
                show: true,
                lineStyle: {
                  color: '#D9E1F3', // 设置 x 轴线的颜色
                  width: 1 // 设置 x 轴线的宽度
                }
            },
            axisLabel: {
                show: true,
                textStyle: {
                  color: '#999999',
                  fsize: 12
                }
            }
        },
        yAxis: {
            type: 'value',
            minInterval:1,
            splitLine:{
                show: true,
                lineStyle: {
                    type: 'dashed',
                    color: '#D9E1F3',
                }
            },
            axisTick:{
                show: false
            },
            axisLine: {
                show: true,
                lineStyle: {
                  color: '#D9E1F3', // 设置 x 轴线的颜色
                  width: 1 // 设置 x 轴线的宽度
                }
            },
            axisLabel: {
                show: true,
                textStyle: {
                  color: '#999999',
                  fsize: 12
                }
            }
        },
        series: series,
    };

    myChart && myChart.setOption(option)
};
const resize = () => {
    let myChart = echarts.init(document.getElementById("chartRef2"));
    myChart.resize()
}
onMounted(() => {
    initChart();
    window.addEventListener('resize', resize)
});

watch(
    () => props.data,
    () => {
        console.log('变化');

        initChart();
    },
    { deep: true }
);
onBeforeUnmount(() => {
    window.removeEventListener('resize', resize)
})
</script>

<style scoped>
.chart-container {
    width: 100%;
    height: 400px;
    /* 根据需求调整高度 */
}
</style>